package com.share.tool.m2d.utils;


import com.share.tool.m2d.enums.DbEnum;
import com.share.tool.m2d.enums.RdsEnum;
import com.share.tool.m2d.model.DrdsConf;
import com.share.tool.m2d.model.DrdsRouter;
import lombok.extern.slf4j.Slf4j;

import java.text.DecimalFormat;

/**
 * @author syq
 * @data 2019/11/15
 */
@Slf4j
public class DrdsRouterUtil {
    public static DrdsRouter hash(String env, String tableName, String nick) {
        if (nick == null || tableName==null || tableName.trim().length()==0) {
            return null;
        }

        if(DbEnum.toEnum(env)==null){
            return  null;
        }

        Integer hashCode = nick.hashCode();
        Integer tmp = hashCode % (DrdsConf.instance * DrdsConf.db * DrdsConf.table);
        if (tmp < 0) {
            tmp = 0 - tmp;
        }

        DrdsRouter dr = new DrdsRouter();
        int instanceNum = (tmp / DrdsConf.table / DrdsConf.db);
        int dbNum=(tmp  / DrdsConf.table);
        int tableNum=(tmp % (DrdsConf.instance * DrdsConf.db * DrdsConf.table));

        DecimalFormat tableFormat = new DecimalFormat("_000");
        DecimalFormat dbFormat = new DecimalFormat("0000");

        dr.setTableName(tableName+tableFormat.format(tableNum));/*设定表名*/
        dr.setHash(tableNum);

        RdsEnum rds =  RdsEnum.toEnumByInstanceId(instanceNum);
        dr.setRdsIp(rds.getIp());/*设定ip*/
        dr.setRdsName(rds.getSelfName());
        dr.setRdsDomain(rds.getDomain());

        DbEnum db = DbEnum.toEnum(env);
        dr.setDbName(db.getTagName()+dbFormat.format(dbNum));/*设定数据库名字*/
        dr.setUsername(db.getUsername());
        dr.setPassword(db.getPassword());
        return dr;
    }


    public static void main(String arr[]) {
        DrdsRouter hash = hash("test","bbt_jd_member","tydic-bbt");
        System.out.println(hash);
    }

}
